package com.sanji.sjmallmodule.login;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.sanji.sjmallapp.BaseActivity;
import com.sanji.sjmallapp.R;
import com.sanji.sjmallconfig.ConfigAPI;
import com.sanji.sjmallconfig.ConfigConts;
import com.sanji.sjmallmanager.http.NoHttpCallBack;
import com.sanji.sjmallmanager.http.NoHttpListener;
import com.sanji.sjmallutils.Tools;
import com.yolanda.nohttp.NoHttp;
import com.yolanda.nohttp.RequestMethod;
import com.yolanda.nohttp.rest.Request;
import com.yolanda.nohttp.rest.Response;

import org.json.JSONException;
import org.json.JSONObject;

import butterknife.BindView;
import butterknife.ButterKnife;

/*
 * 设置密码
 */
public class ResetPasswordActivity extends BaseActivity implements View.OnClickListener, NoHttpListener {
    @BindView(R.id.clear_phone_number)
    ImageView clearNumber;
    @BindView(R.id.request_phone_code)
    TextView requestPhoneCodeTv;
    @BindView(R.id.reset_password_btn)
    Button resetPasswordBtn;
    @BindView(R.id.phone_number_edit)
    EditText phoneNumberEdit;
    private TextView commonTitle;
    private ImageView backImage;
    private String phoneNumber;
    private String phoneCode;
    private int time = 0;
    private int enteType = 0;//跳转入口
    private Request<JSONObject> request;
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {


            }
            super.handleMessage(msg);
        }
    };
    private Runnable runnable = new Runnable() {
        @Override
        public void run() {
            if (time > 0) {
                requestPhoneCodeTv.setText(String.format(getString(R.string.reset_pwd_time_toast),time));
                requestPhoneCodeTv.setTextColor(getResources().getColor(R.color.colorRed));
                requestPhoneCodeTv.setEnabled(false);
                mHandler.postDelayed(this, 1000);
            } else {
                requestPhoneCodeTv.setEnabled(true);
                requestPhoneCodeTv.setText(getString(R.string.reset_pwd_code));
                requestPhoneCodeTv.setTextColor(getResources().getColor(R.color.colorDarkGrey));
            }
            time--;

        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_reset_password);
        ButterKnife.bind(this);
        initView();
    }

    /**
     * 数据的初始化
     */
    public void initView() {
        commonTitle = (TextView) findViewById(R.id.common_title_tv);
        commonTitle.setVisibility(View.VISIBLE);
        backImage = (ImageView) findViewById(R.id.common_back_img);
        enteType = getIntent().getIntExtra("enteType", 0);
        if (enteType == 0) {
            commonTitle.setText(getString(R.string.password_title));
        } else if (enteType == 1) {
            commonTitle.setText(getString(R.string.reset_pwd_modify));
        }
        backImage.setOnClickListener(this);
        clearNumber.setOnClickListener(this);
        requestPhoneCodeTv.setOnClickListener(this);
        resetPasswordBtn.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.common_back_img:
                finish();
                break;
            case R.id.clear_phone_number:
                phoneNumberEdit.setText("");
                break;
            case R.id.request_phone_code:
                sendCheckCode();
                //测试倒计时
                time = 20;
                mHandler.postDelayed(runnable, 1000);
                requestPhoneCodeTv.setEnabled(false);
                break;
            case R.id.reset_password_btn:
                submitRequest();
                break;

        }
    }

    /**
     * 发送验证码
     */
    public void sendCheckCode() {
        phoneNumber = phoneNumberEdit.getText().toString();
        if ("".equals(phoneNumber) || phoneNumber == null) {
            Tools.toastTools(mCtx, getString(R.string.register_input_phone));
            return;
        }
        JSONObject json = new JSONObject();
        try {
            json.put("mobile", phoneNumber);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        request = NoHttp.createJsonObjectRequest(ConfigAPI.MOBILECODE_URL, RequestMethod.GET);
        request.setDefineRequestBodyForJson(json);
        request.setCancelSign(ConfigAPI.MOBILECODE_URL.hashCode());
        NoHttpCallBack.getInstance().add(mCtx, ConfigAPI.MOBILECODE_URL.hashCode(), request, this, true, true);
    }

    /**
     * 确认提交
     */
    public void submitRequest() {
        //测试
        intent = new Intent(this, ChangePasswordActivity.class);
        startActivity(intent);
        //发送请求
        phoneCode = requestPhoneCodeTv.getText().toString().trim();
        if ("".equals(phoneNumber) || phoneNumber == null) {
            Tools.toastTools(mCtx, getString(R.string.register_input_phone));
            return;
        }
        if (TextUtils.isEmpty(phoneCode)) {
            Tools.toastTools(mCtx, getString(R.string.reset_pwd_input_code));
            return;
        }
        String url = ConfigAPI.TEST_MOBILE_URL + "mobile=" + phoneNumber + "&code=" + phoneCode;
        request = NoHttp.createJsonObjectRequest(url, RequestMethod.GET);
        request.setCancelSign(ConfigAPI.TEST_MOBILE_URL.hashCode());
        NoHttpCallBack.getInstance().add(mCtx, ConfigAPI.TEST_MOBILE_URL.hashCode(), request, this, true, true);
    }

    @Override
    public void onSuccessed(int what, Response response) {
        int requestCode = response.getHeaders().getResponseCode();
        if (what == ConfigAPI.MOBILECODE_URL.hashCode()) {
            if (requestCode == 200) {
                JSONObject json = (JSONObject) response.get();
                String status = json.optString(ConfigConts.STATUS_STRING);
                if (status.equals(ConfigConts.STATUS_SUCCESS)) {
                    time = 60;
                    mHandler.postDelayed(runnable, 1000);
                    requestPhoneCodeTv.setEnabled(false);
                } else if (status.equals(ConfigConts.STATUS_ERROR)) {
                    String errorMsg = json.optString(ConfigConts.ERRORMSG);
                    Tools.toastTools(mCtx, errorMsg);
                }
            } else {
                Tools.toastTools(mCtx, getString(R.string.reset_pwd_get_code_false));
            }
        } else if (what == ConfigAPI.TEST_MOBILE_URL.hashCode()) {
            if (requestCode == 200) {
                JSONObject jsonObject = (JSONObject) response.get();
                String status = jsonObject.optString(ConfigConts.STATUS_STRING);
                if (status.equals(ConfigConts.STATUS_SUCCESS)) {
                    String sucessMsg = jsonObject.optString(ConfigConts.SUCCESSMSG);
                    Tools.toastTools(mCtx, sucessMsg);
                    intent = new Intent(this, ChangePasswordActivity.class);
                    startActivity(intent);
                } else {
                    String errorMsg = jsonObject.optString(ConfigConts.ERRORMSG);
                    Tools.toastTools(mCtx, errorMsg);
                }
            }
        }
    }

    @Override
    public void onFailed(int what, Response response) {
        if (what == ConfigAPI.MOBILECODE_URL.hashCode()) {
            Tools.toastTools(mCtx, getString(R.string.request_false));
        } else if (what == ConfigAPI.TEST_MOBILE_URL.hashCode()) {
            Tools.toastTools(mCtx, getString(R.string.request_false));
        }
    }
}
